<?php
/*
 * Title: functions.php
 * Description: Core PHP functions for proofGallery
 * Package: proofGallery ver. 0.2
 * Author: Jesse Grobstein
 * Organization: I Services, Inc.
 * URI: http://iservicesinc.net
*/
// uncomment for error reporting
// ini_set('display_errors', 1);
// ini_set('log_errors', 1);
// ini_set('error_log', dirname(__FILE__) . '/error_log.txt');
// error_reporting(E_ALL);
define(root_dir, dirname(__FILE__));
global $admin, $email, $timestamp;
if(file_exists("config.php")) require_once('config.php');
$key = $admin;
$timestamp = date("G:i:s a T - l F jS, Y");

/*** Print HTML Parts ***/
function printHead() {
$head = "<!doctype html>
<html>
<head>
	<title>proofGallery</title>
	<script type='text/javascript' src='http://code.jquery.com/jquery-latest.js'></script>
	<script>
	if(!window.jQuery) {
	   var script = document.createElement('script');
	   script.type = 'text/javascript';
	   script.src = 'lib/jquery.js';
	   document.getElementsByTagName('head')[0].appendChild(script);
	}
	</script>
	<script type='text/javascript' src='http://code.jquery.com/ui/jquery-ui-git.js'></script>
	<script src='lib/script.js'></script>
	<link href='source/style.css' rel='stylesheet' type='text/css' />
	<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300' rel='stylesheet' type='text/css' />
	<link rel='stylesheet' href='http://code.jquery.com/ui/jquery-ui-git.css' type='text/css' media='all' />
	<link rel='stylesheet' type='text/css' href='source/jquery.fancybox.css?v=2.1.0' media='screen' />
	<link rel='stylesheet' type='text/css' href='source/helpers/jquery.fancybox-buttons.css?v=1.0.3' />
	<link rel='stylesheet' type='text/css' href='source/helpers/jquery.fancybox-thumbs.css?v=1.0.6' />
</head>
<body>
	<header>
		<h1>proofGallery <sup>ver. 0.2</sup></h1>
	</header>
	<content>
	<noscript><p>This page requires a javascript enabled browser! Please enable Javascript or re-visit this page with a Javascript enabled browser to view your photos.</p></noscript>
	";
echo $head;
}
function printFoot() {
$year = date("Y");
$foot = "
	</content>
	<footer>
		<h6 style='clear:none;float:left;'>&laquo; Darker</h6>
		<h6 style='clear:none;float:right;'>Lighter &raquo;</h6>
		<div id='cbcSlider' style='clear:both'></div><br/>
		<p class='copy center'>&copy; $year <a href='http://iservicesinc.net' title='I Services, Inc.'>I Services, Inc.</a></p>
		<a href='http://www.gnu.org/licenses/gpl.txt' title='GNU General Public License' target='_blank'><img id='gpl' src='http://www.gnu.org/graphics/gplv3-88x31.png' alt='GNU General Public License'/></a>
	</footer>
</body>
<script type='text/javascript' src='source/jquery.fancybox.js?v=2.1.0'></script>
<script type='text/javascript' src='lib/jquery.mousewheel-3.0.6.pack.js'></script>
<script type='text/javascript' src='source/helpers/jquery.fancybox-buttons.js?v=1.0.3'></script>
<script type='text/javascript' src='source/helpers/jquery.fancybox-thumbs.js?v=1.0.6'></script>
<script type='text/javascript' src='source/helpers/jquery.fancybox-media.js?v=1.0.3'></script>
</html>";
echo $foot;
}
// Admin Section
set_time_limit(0);
$uploadForm = "<h2>Upload New Album:</h2><form id='upload' action='{$_SERVER['PHP_SELF']}?admin={$admin}' enctype='multipart/form-data' method='post'><label>Choose a zip file to upload: <input id='file' type='file' name='file' /></label><input class='btn' type='submit' value='Upload' /></form>";
function admin_init() {
	$dh = opendir('./albums') or die("<p>There was an error reading your albums.</p>");
	echo "<ul>\n\r";
	while ($file = readdir($dh)) {
		if($file == '.' || $file == '..' || $file == 'index.php') continue;
		$uid = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $file, MCRYPT_MODE_CBC, md5(md5($key))));
		if(file_exists($file.".txt")) {
				$approval = "Approved"; 
				$css="style='text-decoration:strikethrough;'";
				$link= "{$file}.txt";
			} else {
				$approval = "Pending"; 
				$css="style='text-decoration:none;'";
				$link= "?UID={$uid}";
		}
		echo "<li {$css}><a href='{$link}' title='{$file}' target='_blank'>{$file}</a> [{$approval}]<br/><span class='context' contenteditable>http://{$_SERVER['SERVER_NAME']}/proofGallery/?UID={$uid}</span><br/></li>";
	}
	closedir($dh);
	echo "</ul>\n\r";
}
function createThumbs($dir) {
	$src = root_dir . "/albums/" . $dir . "/original/";
	$dest = root_dir . "/albums/" . $dir . "/thumb/";
	$desired_width = 175;
	if(!file_exists($dest)) {  
	  if(!mkdir($dest)) {
			chmod(root_dir . "/albums/" . $dir, 0777);
			if(!mkdir($dest)) die("<b>mkdir():</b> Failed to create $target_path");
		}
	  // if(!chmod($dest, 0777)) {die("chmod: Access Denied!");}
	}
	$dh = opendir($src) or die("<p>There was an error reading your albums.</p>");
	while ($file = readdir($dh)) {
		if($file == '.' || $file == '..') continue;
		/* read the source image */
		$source_image = imagecreatefromjpeg($src.$file);
		$width = imagesx($source_image);
		$height = imagesy($source_image);
		/* find the "desired height" of this thumbnail, relative to the desired width  */
		$desired_height = floor($height * ($desired_width / $width));
		/* create a new, "virtual" image */
		$virtual_image = imagecreatetruecolor($desired_width, $desired_height);
	 	/* copy source image at a resized size */
		imagecopyresampled($virtual_image, $source_image, 0, 0, 0, 0, $desired_width, $desired_height, $width, $height);
	 	/* create the physical thumbnail image to its destination */
		imagejpeg($virtual_image, "{$dest}{$file}");
	}
	closedir($dh);
}
if(isset($_FILES['file'])) {
	$tmpfile = basename($_FILES["file"]["name"]);
	$source = $_FILES["file"]["tmp_name"];
	$type = $_FILES["file"]["type"];
	$name = explode(".", $tmpfile);
	$target_path = root_dir .'/albums/'. $name[0];
	$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
	foreach($accepted_types as $mime_type) {
		if($mime_type == $type) {
			$okay = true;
			break;
		} 
	}
	$continue = strtolower($name[1]) == 'zip' ? true : false;
	if(!$continue) {
		$message = "The file you are trying to upload is not a .zip file. Please try again.";
	}
	if(!file_exists($target_path)) {  
	  if(!mkdir($target_path)) { 
		$albums_dir = root_dir . '/albums';
		chmod($albums_dir, 0777) or die("<b>chmod():</b> Failed to modify $albums_dir");
		if(!mkdir($target_path)) die("<b>mkdir():</b> Failed to create $target_path");
	  }
	  // if(!chmod($target_path, 0777)) die("chmod: Access Denied!");
	}  
	if($_FILES["file"]["tmp_name"]) {
		$zip = new ZipArchive();
		$x = $zip->open($_FILES["file"]["tmp_name"]);
		if ($x === true) {
			if(!file_exists($target_path . '/original')) 
				mkdir($target_path . '/original', 0777);
			$zip->extractTo($target_path . '/original');
			$zip->close();
		} else { die("zip: Failed!"); }	
		createThumbs($name[0]);
		$message = "Your .zip file was uploaded and unpacked.";		
	} else {	
		$message = "There was a problem with the upload. Please try again.";
	}
}

/*** Gallery Configuration Start ***/
function gallery_init() {
	if(isset($_GET['UID'])) {
	global $admin, $email, $timestamp, $user, $thumb_directory, $orig_directory, $stage_width, $stage_height, $allowed_types, $file_parts, $ext, $title, $i;
	$user = $_GET['UID'];
	$user = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($user), MCRYPT_MODE_CBC, md5(md5($key))), "\0");
	$thumb_directory = 'albums/' . $user . '/thumb';
	$orig_directory = 'albums/' . $user . '/original';
	$allowed_types = array('jpg','jpeg','gif','png');
	$file_parts = array();
	$ext = '';
	$title = '';
	$i=0;
	} elseif(!isset($_GET['admin'])) {
	echo "<p>This page requires a unique link to view your gallery. Please re-visit this page with the link provided by email to proof your photos.</p>";
	}
	if(isset($_POST['approvePhotos'])) {
		$list = "Approved Photos:\n";
		foreach($_POST['picid'] as $pic) {
			$list .= "$pic \n";
		}
		$message = "Automated Mail From: {$_SERVER['SERVER_NAME']}\n\n{$list}\n\nApproved by: {$user} at {$timestamp}";
		// $htmlmsg = str_replace("\n", "<br/>", $message);
		if(mail($email, 'Photo Approval From - '.$user, $message))
			echo "<p>Your approval has been emailed to <a href='mailto:{$email}'>{$email}</a>. If you have any questions or concerns, feel free to contact me!</p></div>";
			$fh = fopen($user.'.txt', 'a'); 
			fwrite($fh, $message); 
			fclose($fh);
		exit();
	}
}
?>